package com.uminho.egendme;


import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.MonthDisplayHelper;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.Action;
import com.uminho.calendar.CalendarView;
import com.uminho.calendar.Cell;
import com.uminho.calendar.DayDialog;
import com.uminho.exceptions.InvalidOAuthParametersError;
import com.uminho.exceptions.InvalidOAuthTokenError;
import com.uminho.http.InternalStorage;
import com.uminho.http.Webservice;
import com.uminho.objects.Appointment;
import com.uminho.tools.Disponibilidades;

/****c* egendme/Calendar
 * DESCRIPTION
 * Classe responsável por oferecer suporte à actividade Calendario
 *
 ****
 */
 
public class Calendar extends Activity implements CalendarView.OnCellTouchListener{
	//public static final String MIME_TYPE = "vnd.android.cursor.dir/vnd.com.uminho.calendar.date";
	CalendarView mView = null;
	TextView mHit;
	Handler mHandler = new Handler();
	TextView actualMonthTitle, lastMonthTitle, nextMonthTitle;
	ImageView prev, next;
	DayDialog dialog; Button confirmDialog;
	HashMap<Date,Integer> infoCalendars;
	ProgressDialog myProgressDialog = null; 
	Handler messages=null;
	ArrayList<Appointment> slots;
	int day, month, year;
	boolean offline=false;
	String[] monthName = {"January", "February",
  		  "March", "April", "May", "June", "July",
  		  "August", "September", "October", "November",
  		  "December"
  };

	
	
	/****f* Calendar/onCreate
	 * DESCRIPTION
	 * Método executado para criar a actividade
	 * INPUTS
	 * Estado da aplicação
	 * RESULT
	 * Actividade criada
	 *
	 ****
	 */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.calendar_table_layout);
        ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
		actionBar.setHomeAction(new Action() {
			
			public void performAction(View view) {
				finish();
			}
			
			public int getDrawable() {
				return R.drawable.icon1;
			}
		});
		actionBar.setTitle(R.string.user_calendar);
        //SharedPreferences preferences = getSharedPreferences("com.uminho.egendme_preferences",MODE_PRIVATE);
        //SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        //Log.d("teste", "pref: "+preferences.getAll().toString());
        
      
        
        /*
         * Informa?‹o dos calendarios
         * exemplo!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
         */
        
        mView = (CalendarView)findViewById(R.id.calendar);
        if(Disponibilidades.busyDays==null){
            infoCalendars = new HashMap<Date,Integer>();
            mView.setBusyDays(infoCalendars);
            Log.d("Calendar disponibilidades", "vazias!!!!");
    		}
        else {
        	mView.setBusyDays(Disponibilidades.busyDays);
        	infoCalendars=Disponibilidades.busyDays;
        }
        
        mView.setOnCellTouchListener(this);
        
        
        
        //set month title
        actualMonthTitle = (TextView) findViewById(R.id.textViewCalendarMonth);
        actualMonthTitle.setText(monthName[mView.getMonth()]+", "+mView.getYear());
        
        MonthDisplayHelper calendarAux = new MonthDisplayHelper(mView.getYear(), mView.getMonth());
        calendarAux.previousMonth();
       prev = (ImageView) findViewById(R.id.prev);
        prev.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				mView.previousMonth();
				onTouch(null);
			}
		}
		);
        
        calendarAux.nextMonth();
        calendarAux.nextMonth();
        /*nextMonthTitle = (TextView) findViewById(R.id.textViewCalendarNextMonth);
        nextMonthTitle.setText(shortMonthName[calendarAux.getMonth()]);*/
        next = (ImageView) findViewById(R.id.next);
        next.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				mView.nextMonth();
				onTouch(null);
			}
		}
		);
        
    }

    @Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		//Log.d("Dashboard", "actvityRequest "+requestCode+" "+resultCode);
		if(resultCode==2){
			Log.d("Favorites", "finish");
			finish();
		}
		else if(resultCode==3){
			Log.d("Favorites", "refresh");
			Intent refresh = new Intent(this, Agenda.class);
			startActivity(refresh);
			this.finish();

		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	private void reload(){
		Intent refresh = new Intent(this, Agenda.class);
		startActivity(refresh);
		this.finish();
	}
    /****f* Calendar/onTouch
	 * DESCRIPTION
	 * Método executado para receber as células carregadas
	 * INPUTS
	 * Célula do calendario
	 * RESULT
	 * Trata a Celula clicada
	 *
	 ****
	 */
	public void onTouch(Cell cell) {
		if(cell!=null){
			day = cell.getDayOfMonth();
			month = mView.getMonth();
			year = mView.getYear();
			
			if(mView.isLastMonth(cell)){
				//update view
		        mView.previousMonth();
			}
			else if(mView.isNextMonth(cell)){
				//update view
				mView.nextMonth();
			}	
			else {
				
				if(messages==null){
			        messages = new Handler() {
				        @Override
						public void handleMessage(Message msg) {
				        	if(msg.what==1){
								if(offline) Toast.makeText(Calendar.this, getString(R.string.working_offline), 3000).show();
				        		
								dialog = new DayDialog(Calendar.this, slots, new GregorianCalendar(year,month,day));
								dialog.setTitle(day+" "+monthName[mView.getMonth()]+", "+mView.getYear());
								dialog.show();
					        	//Toast.makeText(Calendar.this, "Appointments nr: "+slots.size(), 3000).show();
									
				        	}
				        	else if(msg.what==-1){
								//token/auth error
				        		Log.d("Calendar", "invalid token");
								myProgressDialog.dismiss();
								Toast.makeText(Calendar.this, getString(R.string.autentication_error), Toast.LENGTH_LONG).show();
								setResult(2);
								InternalStorage.goLoggin(Calendar.this);
							}
							else /*if(msg.what==-2)*/{
								//connection error
								Log.d("Calendar", "connection error");
								myProgressDialog.dismiss();
								Toast.makeText(Calendar.this, getString(R.string.impossiblereachtheserver), Toast.LENGTH_LONG).show();		        		
							}
				        	
				        	
				        }
				    };
				}
				
				GregorianCalendar aux = new GregorianCalendar(year,month,day);
				
		if(infoCalendars.get(aux.getTime())!=null){
			
				
				myProgressDialog = ProgressDialog.show(Calendar.this, getString(R.string.loading), getString(R.string.getDayView), true);			
				new Thread() {
					@Override
					public void run() {
						/**
						 * 
						 * aqui vai receer o webservice
						 * 
						 * 
						 */
						try {
							
							Webservice w = Webservice.getInstance();
							slots=null;
							slots=w.GetAppointments();
							
							
							if(slots!=null && slots.size()>0)
							InternalStorage.saveAppointments(slots);
							
							Log.d("Calendar get appointments", "number: "+slots.size());
						}catch (InvalidOAuthTokenError e) {
							messages.sendEmptyMessage(-1);
							Log.d("Calendar", "token error loading bookmarks");
							return;
						}catch (InvalidOAuthParametersError e) {
							messages.sendEmptyMessage(-1);
							Log.d("Calendart", "autentication error loading bookmarks");
							return;
						} 
						catch (Exception e) {
							if(slots==null || slots.size()<=0){
								 try{
							        	slots=InternalStorage.readAppointments();
							        	offline=true;
							        }catch (Exception ex)
							        {
							        Log.d("Offline Favorites", e.toString());
							        }
								 
							}
							if(slots==null || slots.size()<=0){
							messages.sendEmptyMessage(-2);
							Log.d("Favorites", "error loading Favorites");
							return;
							}
						} 
						myProgressDialog.dismiss();
						messages.sendEmptyMessage(1);
					
					}

					}.start();
					
		}
		else Toast.makeText(Calendar.this, this.getString(R.string.no_appointment_day), 3000).show();
					
			
			}
			}
		actualMonthTitle.setText(monthName[mView.getMonth()]+", "+mView.getYear());
		MonthDisplayHelper calendarAux = new MonthDisplayHelper(mView.getYear(), mView.getMonth());
        calendarAux.previousMonth();
        //lastMonthTitle.setText(calendarAux.getMonth()+1+"");
        calendarAux.nextMonth();
        calendarAux.nextMonth();
        //nextMonthTitle.setText(calendarAux.getMonth()+1+"");
        
	}
	
}
